package com.wswy.wzcx.ui.pay

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import com.blankj.utilcode.util.RegexUtils
import com.che.libcommon.utils.RxBus
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.ConfigsKt
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.PaymentOrder
import com.wswy.wzcx.model.core.EventNormal
import com.wswy.wzcx.model.core.postEvent
import com.wswy.wzcx.model.coupon.CouponModel
import com.wswy.wzcx.model.coupon.CouponResp
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.gone
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.module.base.visible
import com.wswy.wzcx.module.pay.PayManager
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.coupon.ChooseCouponFragment
import com.wswy.wzcx.ui.dialog.FullHintAlertDialog
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.fkdj.FineData
import com.wswy.wzcx.ui.other.CloseDelegate
import com.wswy.wzcx.ui.web.WebViewActivity
import com.wswy.wzcx.utils.StringUtils
import com.wswy.wzcx.utils.getColor
import kotlinx.android.synthetic.main.fragment_pay_order.*
import timber.log.Timber

/**
 * 订单支付
 */
class PayOrderFragment : CBaseFragment() {


    companion object{
        @JvmStatic
        fun newInstance() = PayOrderFragment()

        private const val REQ_CHOOSE_COUPON = 106
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_pay_order
    }

    override fun getFragmentTitle(): String {
        return "订单确认"
    }

    private lateinit var payOrderViewModel: PayOrderViewModel

    private val loadingDialog: LoadingDialog by lazy {
        LoadingDialog(requireContext(),"处理中")
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val data= arguments?.getParcelable<PayOrder?>(Constants.EXTRA_DATA)

        if (data?.data == null || data.type <= 0){
            finish()
            return
        }else{

            payOrderViewModel = provideViewModel(PayOrderViewModel::class.java)
            payOrderViewModel.onCreate()

            payOrderViewModel.payOrder = data

            val res =  data.data
            if (data.type == PayOrder.TYPE_FKDJ && res is PreFineInfo){
                showFine(res)
            } else if (data.type == PayOrder.TYPE_WZDB && res is PayWzdbData){
                showWzdb(res)
            } else if(data.type == PayOrder.TYPE_NJDB && res is PayNjdbData){
                showNjdb(res)
            }else{
                finish()
                return
            }

        }

        initViews()

    }

    private fun initViews(){

        pay_layout.selectedCallback = {
            payOrderViewModel.setPayStyle(it.code)
        }
        //默认支付方式
        payOrderViewModel.setPayStyle(pay_layout.getPayStyle().code)


        img_choose.onClick {
            img_choose.isSelected= !img_choose.isSelected
        }
        img_choose.isSelected = true

        btn_pay.onClick {

            if (img_choose.isShown && !img_choose.isSelected){
                ToastUtils.showText("请先同意服务协议")
                return@onClick
            }

            //去支付
            when(payOrderViewModel.payOrder.type){
                PayOrder.TYPE_WZDB -> {
                    startWzdbPay()
                }
                PayOrder.TYPE_FKDJ -> {
                    startFinePay()
                }
                PayOrder.TYPE_NJDB -> {
                    startNjdbPay()
                }
            }
        }
        //优惠券
        rl_coupon.onClick {
            startActivityForResult(ModuleActivity.getTargetIntent(it.context, ChooseCouponFragment.TAG).apply {
                putExtra(Constants.EXTRA_DATA_ID,payOrderViewModel.getPayBaseData()?.couponId)
            },REQ_CHOOSE_COUPON)

        }

        payOrderViewModel.getOrderPayResultLiveData().observe(this, Observer {
            it?.runCatching {
                if (status){
                    //支付成功
                    ToastUtils.showText("支付成功")
                    startPaySuccess(order)
                }
            }
        })

        payOrderViewModel.getPayOrderStatusLiveData().observe(this, Observer {
            it?.runCatching {

                if (inLoading()){
                    safeWindow(true)
                    loadingDialog.startLoading("处理中")
                }else{
                    safeWindow(false)
                    if (data?.payStatus == true){
                        //支付成功
                        loadingDialog.setOnDismissListener {
                            startPaySuccess(payOrderViewModel.paymentOrder!!)
                            safeWindow(false)
                        }
                        loadingDialog.setSuccess("支付成功")

                    }else{
                        //支付失败
                        loadingDialog.setSuccess("已取消")
                    }
                }

            }
        })

        payOrderViewModel.getCouponRespLiveData().observe(this, Observer {
            it?.runCatching {
                if (isHidden){
                    return@Observer
                }
                if (isOk()){
                    showDefaultCouponTitle(data)
                }

            }
        })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK && requestCode == REQ_CHOOSE_COUPON){

            data?.getParcelableExtra<CouponModel?>(Constants.EXTRA_DATA)?.let {

                tv_coupon_choose.text = getString(R.string.coupon_reduce,it.amountStr)
                tv_coupon_choose.setTextColor(getColor(R.color.accentColor3))
                payOrderViewModel.setCoupon(it.id,it.amount,it)

            }?:kotlin.run {

                showDefaultCouponTitle(payOrderViewModel.getCouponRespLiveData().value?.data)
                payOrderViewModel.setCoupon(0,"",null)
            }

        }

    }

    private fun safeWindow(lock:Boolean){
        if (lock){
            ll_bottom.setOnTouchListener { v, event ->
                true
            }
            scroll_view.setOnTouchListener { v, event ->
                true
            }
        }else{
            ll_bottom.setOnTouchListener(null)
            scroll_view.setOnTouchListener(null)
        }


    }


    private fun showDefaultCouponTitle(data: CouponResp?){
        if (data == null){
            rl_coupon.gone()
            return
        }

        if (payOrderViewModel.getPayBaseData()?.hasCouponFee() == true){
            return
        }
        rl_coupon.visible()
        if (data.list.isNullOrEmpty()){
            if (TextUtils.isEmpty(data.activityModel?.name)) {
                //也没有活动
                tv_coupon_choose.text = "无可用优惠券"
            }else{
                tv_coupon_choose.text = data.activityModel?.name
            }
            tv_coupon_choose.setTextColor(getColor(R.color.textColorPrimary_40))
        }else{
            tv_coupon_choose.setTextColor(getColor(R.color.accentColor3))
            tv_coupon_choose.text = getString(R.string.coupon_available,data.list.size)
        }
    }

    private fun startPaySuccess(paymentOrder: PaymentOrder){
        ModuleActivity.getTargetIntent(requireContext(),PaySuccessFragment.TAG,Bundle().apply {
                putParcelable(Constants.EXTRA_DATA,PayComplete(paymentOrder.orderNo,
                        paymentOrder.amount,
                        payOrderViewModel.payOrder.type,
                        paymentOrder.payStyle,
                        null))

            }).also {
                startActivity(it)
            }
        RxBus.getDefault().postWithCode(InternalMsgCode.CODE_PAY_SUCCESS,"")
        //支付成功
        postEvent(EventNormal(InternalMsgCode.CODE_PAY_SUCCESS,null))
        finish()
    }


    /////----违章代办

    private fun showWzdb(payWzdbData: PayWzdbData){
        fl_input_phone.visible()
        fl_input_name.visible()
        fl_input_quick.gone()

        tv_title_hint.text = getString(R.string.pay_order_wzdb_hinr,payWzdbData.userCarInfo.carNo,payWzdbData.wzdbOrderInfo.count,payWzdbData.wzdbOrderInfo.point)


        pay_layout.setPayType(PayManager.PAY_TYPE_WZDB)

        tv_service_protocol.text = SpannableStringBuilder().apply {
            append("同意")
            append(SpannableString("《违章代办协议》").apply {
                setSpan(ForegroundColorSpan(getColor(R.color.colorPrimary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }

        tv_service_protocol.onClick {
            WebViewActivity.startWebview(it.context, ConfigsKt.H5_PRO_WZDB())
        }

        DataCenter.get().userMode?.mobile?.runCatching {
            et_phone.setText(this)
            et_phone.setSelection(length)
        }
        payOrderViewModel.getLastContactName()?.runCatching {
            if (isNotEmpty()){
                et_name.setText(this)
                et_name.setSelection(length)
            }
            et_name.requestFocus()
        }
        payOrderViewModel.setWzdbData(payWzdbData)

        payWzdbData.wzdbOrderInfo.runCatching {

            tv_fine_fee.text = getString(R.string.amount_args,penalty)
            tv_service_fee.text = getString(R.string.amount_args,serviceFee)

            //
            tv_amount_mony.text = getString(R.string.pay_total_money,payWzdbData.getTotalFeeText())

            if (lateFee?.toDoubleOrNull()?:0.0 > 0){
                tv_late_fee.text = getString(R.string.amount_args,lateFee)
            }else{
                tv_left_late_fee_hint.gone()
                tv_late_fee.gone()
                late_fee_view.gone()
            }

        }
        payOrderViewModel.getWzdbLiveData().observe(this, Observer {

            it?.runCatching {
                tv_amount_mony.text = getString(R.string.pay_total_money,payWzdbData.getTotalFeeText())
            }

        })

    }

    private fun startWzdbPay(){
        val phone = et_phone.text
        val name = et_name.text

        if (phone.isNullOrEmpty()){
            ToastUtils.showText("请输入联系电话")
            return
        }
        if (!RegexUtils.isMobileSimple(phone)){
            ToastUtils.showText("请输入正确的手机号码")
            return
        }
        if (name.isNullOrEmpty()){
            ToastUtils.showText("请输入联系人姓名")
            return
        }

        FullHintAlertDialog(context!!)
                .setDelayNext(5)
                .setDialogMessage(R.string.wzdb_pay_hint1, R.string.wzdb_pay_hint2)
                .setLeftText(R.string.think_about, null)
                .setRightText(R.string.continue_pay) {
                    payOrderViewModel.startWzdbPay(requireActivity(),phone.toString(),name.toString())
                }
                .show()
    }


    //罚款代缴
    private fun showFine(fineInfo: PreFineInfo){
        //

        fl_input_phone.visible()
        fl_input_name.gone()
        fl_input_quick.gone()

        payOrderViewModel.setPreFineInfo(fineInfo)

        tv_service_protocol.text = SpannableStringBuilder().apply {
            append("同意")
            append(SpannableString("《罚款代缴协议》").apply {
                setSpan(ForegroundColorSpan(getColor(R.color.colorPrimary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }

        tv_service_protocol.onClick {
            WebViewActivity.startWebview(it.context, ConfigsKt.H5_PRO_FKZB())
        }

        DataCenter.get().userMode?.mobile?.runCatching {
            et_phone.setText(this)
            et_phone.setSelection(length)
        }


        payOrderViewModel.getFineLiveData().value?.runCatching {

            if (fineInfo.quickStatus == true){
                tv_title_hint.text = getString(R.string.pay_order_fkdj_hint1,fineInfo.carNo,fineInfo.fineNo)
            }else{
                tv_title_hint.text = getString(R.string.pay_order_fkdj_hint2,fineInfo.fineName,fineInfo.fineNo)
            }


            if (fineInfo.fineLateFee?.toDoubleOrNull()?:0.0 > 0.0){
                //有滞纳金
                tv_left_late_fee_hint.visible()
                tv_late_fee.text = getString(R.string.amount_args,lateFeeText)
                late_fee_view.visible()
            }else{
                tv_left_late_fee_hint.gone()
                tv_late_fee.gone()
                late_fee_view.gone()
            }

            if (fineInfo.quickStatus == true){
                //有极速代办服务费 则支持

                fl_input_quick.visible()

                fl_input_quick.onClick {
                    switch_quick_payment.toggle()

                    payOrderViewModel.setQuickService(switch_quick_payment.isChecked)

                }
            }else{
                //不支持
                fl_input_quick.gone()

            }

            tv_fine_fee.text = getString(R.string.amount_args,fineFeeText)
            tv_service_fee.text = getString(R.string.amount_args,getServiceFeeText())

        }

        payOrderViewModel.getFineLiveData().observe(this, Observer {

            it?.runCatching {

                //总金额
                tv_amount_mony.text = getString(R.string.pay_total_money,getTotalFeeText())
                tv_service_fee.text = getString(R.string.amount_args,getServiceFeeText())


            }

        })

    }

    private fun startFinePay(){
        FullHintAlertDialog(requireContext())
                .setDialogMessage( if(payOrderViewModel.getFineLiveData().value?.quickService == true) R.string.fkdj_quick_pay_hint1 else R.string.fkdj_pay_hint1,
                        R.string.fkdj_pay_hint2)
                .setDelayNext(5)
                .setLeftText(R.string.think_about, null)
                .setRightText(R.string.continue_pay) {

                    payOrderViewModel.startFinePay(requireActivity())

                    StatTools.sendClick(context, StatisticsId.clickFKDJ_Pay)
                }.show()
    }



    // 年检代办
    private fun showNjdb(payNjdbData: PayNjdbData){

        payOrderViewModel.setNjdbData(payNjdbData)

        fl_input_phone.gone()
        fl_input_name.gone()
        fl_input_quick.gone()
        ll_tips_njdb.visible()

        ll_choose_protocol.gone()


        tv_title_hint.text = getString(R.string.pay_order_njdb_hint,payNjdbData.userCarInfo.carNo)

        tv_njdb_hint_title.text = getString(R.string.pay_order_njdb_title,payNjdbData.userCarInfo.carNo)

        tv_left_fine_fee_hint.gone()
        tv_fine_fee.gone()

        tv_left_late_fee_hint.gone()
        tv_late_fee.gone()
        late_fee_view.gone()

        tv_left_service_fee_hint.visible()
        tv_service_fee.visible()

        tv_service_fee.text = getString(R.string.amount_args,StringUtils.formatMoney(payNjdbData.orderData.amount))

        tv_amount_mony.text = getString(R.string.pay_total_money,StringUtils.formatMoney(payNjdbData.orderData.amount))

    }


    private fun startNjdbPay(){
        val act = activity?:return

        FullHintAlertDialog(act)
                .setDialogMessage(R.string.msg_njdb_pay1,R.string.msg_njdb_pay2,R.string.msg_njdb_pay3)
                .setDelayNext(5)
                .setLeftText(R.string.think_about, null)
                .setRightText(R.string.continue_pay) {
                    payOrderViewModel.startNjdbPay(act)

                }.show()
    }

    override fun onResume() {
        super.onResume()
        payOrderViewModel.reloadCouponList()
        payOrderViewModel.consumeOrderPayResult()
        payOrderViewModel.checkPay()
    }

}